<template>
  <upload-excel :on-success="onSuccess" />

</template>

<script>
import { reqImportEmployee } from '@/api/employees'
export default {
  name: 'Import',
  methods: {
    // 导入Excel数据成功回调函数
    async onSuccess(data) {
      // data表示读取到的Excel中的最终数据
      const list = this.translateData(data.results)
      if (list && list.length > 0) {
        const ret = await reqImportEmployee(list)
        if (ret.code === 10000) {
          this.$message.success('批量导入成功')
          //   然后跳转到员工列表页面
          this.$router.push('/employees')
        }
      }
    },
    // 格式化日期
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    },
    translateData(list) {
      // list表示Excel中的数据
      const userRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const result = []
      list.forEach(item => {
        //   单行数据
        const row = {}
        for (const key in item) {
          // 根据中文的key获取英文的key
          const enKey = userRelations[key]
          const value = item[key]
          if (['correctionTime', 'timeOfEntry'].includes(enKey)) {
            row[enKey] = this.formatDate(value)
          } else {
            row[enKey] = value
          }
        }
        // 追加一个人的信息到数组中
        result.push(row)
      })
      return result
    }
  }
}

</script>

<style>

</style>
